package com.baijiayun.live.ui.mainvideopanel

import android.annotation.SuppressLint
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.Observer
import android.text.TextUtils
import android.view.View
import android.widget.FrameLayout
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.activity.LiveRoomBaseActivity
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.pptpanel.MyPadPPTView
import com.baijiayun.live.ui.removeSwitchableFromParent
import com.baijiayun.live.ui.speakerlist.item.Switchable
import com.baijiayun.live.ui.speakerlist.item.SwitchableStatus
import com.baijiayun.live.ui.speakerlist.item.SwitchableType
import com.baijiayun.live.ui.speakpanel.PlaceholderItem
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.models.imodels.IUserModel
import com.baijiayun.livecore.utils.LPLogger
import kotlinx.android.synthetic.main.fragment_pad_main_video.view.*
import kotlinx.android.synthetic.main.bjy_layout_item_video.view.*

/**
 * Created by Shubo on 2019-10-10.
 * 主讲视频窗口
 * 三分屏切换逻辑：
 * 三分屏本地切换ppt在老师区，全屏区（ppt区域）和发言列表
 * 老师仅在全屏老师区
 * 学生仅在发言列表和全屏区
 * 切换可能产生一次切换和两次切换（老师在全屏，学生把自己切全屏时，ppt要切到发言列表）
 */
class MainVideoFragment : BasePadFragment() {
    private val TAG: String = "MainVideoFragment"

    private val routerListener by lazy {
        (activity as LiveRoomBaseActivity).routerListener
    }
    private val videoContainer by lazy {
        view!!.videoContainer
    }

    private val placeholderContainer by lazy {
        view!!.placeHolderContainer
    }

    private val liveRoom by lazy {
        routerViewModel.liveRoom
    }

    private val placeholderItem by lazy {
        val placeholderItem = PlaceholderItem(placeholderContainer, routerListener)
        addSwitchable(placeholderItem)
        placeholderItem
    }

    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                initSuccess()
            }
        }
    }

    private val removeMainVideoObserver by lazy {
        Observer<Switchable?> {
            it?.let {
                removeSwitchable(it)
            }
        }
    }

    private val switch2MainVideoObserver by lazy {
        Observer<Switchable?>{
            it?.let {
                removeSwitchableFromParent(it)
                addSwitchable(it)
            }
        }
    }

    private val classEndObserver by lazy {
        Observer<Unit>{
            showClassEnd()
        }
    }

    companion object {
        fun newInstance() = MainVideoFragment()
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_main_video

    override fun observeActions() {
        placeholderItem.view.item_status_placeholder_tv.text = getString(R.string.pad_leave_room_teacher)
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
    }

    /**
     * 占位图
     */
    private fun showRemoteStatus(isLeave: Boolean, forceLeave: Boolean? = false) {
        if (isLeave || forceLeave == true) {
            placeholderItem.view.item_status_placeholder_iv.setImageResource(R.drawable.base_ic_video_leave)
            placeholderItem.view.item_status_placeholder_tv.text = getString(R.string.pad_leave_room_teacher)
        } else {
            placeholderItem.view.item_status_placeholder_iv.setImageResource(R.drawable.base_ic_video_camera_mute)
            placeholderItem.view.item_status_placeholder_tv.text = getString(R.string.pad_camera_closed)
        }
        var label: String? = ""
        val presenterUser: IUserModel? = liveRoom.presenterUser
        if (presenterUser != null) {
            if (presenterUser.type == LPConstants.LPUserType.Teacher) {
                label = liveRoom.customizeTeacherLabel
                label = if (TextUtils.isEmpty(label)) context?.getString(R.string.live_teacher_hint) else "($label)"
            }
            if (presenterUser.type == LPConstants.LPUserType.Assistant) {
                label = liveRoom.customizeAssistantLabel
                label = if (TextUtils.isEmpty(label)) context?.getString(R.string.live_teacher_hint) else "($label)"
            }
            label = presenterUser.name + label
        }
        placeholderItem.view.item_local_speaker_name.text = if (liveRoom.presenterUser != null) label else ""
        placeholderItem.view.visibility = View.VISIBLE
        placeholderItem.view.item_local_speaker_name.visibility = View.VISIBLE
        if (isLeave) {
            placeholderItem.view.item_local_speaker_name.text = ""
            resetViews()
        }
    }

    private fun resetViews() {
        //占位图切换到老师位置
        if (routerViewModel.mainVideoItem?.isPlaceholderItem != true) {
            val mainItem = routerViewModel.mainVideoItem
            mainItem?.run {
                removeSwitchable(this)
                if (this is LifecycleObserver) {
                    lifecycle.removeObserver(this)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showLocalStatus() {
        placeholderItem.view.item_status_placeholder_iv.setImageResource(R.drawable.base_ic_video_camera_mute)
        placeholderItem.view.item_status_placeholder_tv.text = getString(R.string.pad_camera_closed)
        val teacherLabel = if(TextUtils.isEmpty(liveRoom.customizeTeacherLabel)) getString(R.string.live_teacher_hint) else "(${liveRoom.customizeTeacherLabel})"
        placeholderItem.view.item_local_speaker_name.text = liveRoom.currentUser.name + teacherLabel
        placeholderItem.view.visibility = View.VISIBLE
    }

    private var hasInitLocal = false

    private fun initSuccess() {
        routerViewModel.actionPresenterIn.observe(this, Observer {
            if (routerViewModel.isClassStarted.value == true) {
                if (isPresenter()) {
                    if (!hasInitLocal) {
                        hasInitLocal = true
                        attachLocalAVideo()
                    }
                }
            }
            if (isPresenter()) {
                showLocalStatus()
            } else {
                showRemoteStatus(it.isNullOrEmpty())
            }
        })

        //助教进来
        routerViewModel.showPresenterIn.observe(this, Observer {
            it?.let { showRemoteStatus(false) }
        })

        routerViewModel.isClassStarted.observe(this, Observer {
            it?.let {
                if (it) {
                    if (isPresenter() && !hasInitLocal) {
                        hasInitLocal = true
                        attachLocalAVideo()
                    }
                }
            }
        })
        //下课不能用routerViewModel.isClassStarted = false判断因为获取了初始值
        // routerViewModel.liveRoom.isClassStarted。
        routerViewModel.classEnd.observeForever(classEndObserver)

        routerViewModel.switch2MainVideo.observeForever(switch2MainVideoObserver)

        routerViewModel.removeMainVideo.observeForever(removeMainVideoObserver)
    }

    private fun showPresenterLeave() {
        if (TextUtils.isEmpty(routerViewModel.liveRoom.speakQueueVM.presenter)) {
            showRemoteStatus(true, forceLeave = true)
        } else {
            showClassEnd()
        }
    }

    private fun showClassEnd() {
        if (!routerViewModel.liveRoom.isClassStarted) {
            showRemoteStatus(false)
            resetViews()
            hasInitLocal = false
        }
    }

    private fun addSwitchable(switchable: Switchable) {
        if (switchable.isPlaceholderItem) {
            placeholderContainer.addView(switchable.view)
            if (videoContainer.childCount == 0) {
                routerViewModel.mainVideoItem = switchable
            }
        } else {
            if (switchable.switchableType == SwitchableType.MainItem || switchable.switchableType == SwitchableType.PPT) {
                videoContainer.addView(switchable.view, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
                if (switchable.switchableType == SwitchableType.MainItem) {
                    routerViewModel.mainVideoItem = switchable
                }
            }
        }
    }

    private fun removeSwitchable(switchable: Switchable) {
        //可能在ppt区域和主讲区
        if (!switchable.isPlaceholderItem) {
            removeSwitchableFromParent(switchable)
            if (videoContainer.childCount == 0) {
                //已经remove的switchable是在主讲区
                if (switchable.switchableStatus == SwitchableStatus.MainVideo) {
                    placeholderItem.replaceVideoSync(switchable)
                    routerViewModel.mainVideoItem = placeholderItem
                    showPresenterLeave()
                } else if (switchable.switchableStatus == SwitchableStatus.MaxScreen) {
                    //已经remove的switchable是在ppt区域
                    val pptView = routerViewModel.pptViewData.value
                    if (pptView is MyPadPPTView && switchable.switchableStatus == SwitchableStatus.MaxScreen) {
                        pptView.switch2MaxScreenLocal()
                    }
                }
            } else {
                //当ppt在主讲区，主讲肯定是在ppt区域
                //当ppt在发言列表，肯定是非主讲在ppt区域
                val pptView = routerViewModel.pptViewData.value
                if (pptView is MyPadPPTView) {
                    when (pptView.pptStatus) {
                        SwitchableStatus.MainVideo -> {
                            placeholderItem.replaceVideoSync(switchable)
                            routerViewModel.mainVideoItem = placeholderItem
                            showPresenterLeave()
                        }
                        SwitchableStatus.SpeakList -> {
                            if (switchable.switchableStatus == SwitchableStatus.MaxScreen) {
                                pptView.switch2MaxScreenLocal()
                            }
                        }
                    }

                }
            }
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        placeholderItem.onRemove()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
        routerViewModel.classEnd.removeObserver(classEndObserver)
        routerViewModel.removeMainVideo.removeObserver(removeMainVideoObserver)
        routerViewModel.switch2MainVideo.removeObserver(switch2MainVideoObserver)
    }

    /**
     * 是否是助教
     */
    private fun isPresenter() = routerViewModel.liveRoom.speakQueueVM.isPresenterUser(routerViewModel.liveRoom.currentUser)
}